package com.mall.promo.mq;

import com.alibaba.fastjson.JSON;
import com.mall.promo.cache.CacheManager;
import com.mall.promo.dal.persistence.PromoItemMapper;
import com.mall.promo.dto.SecKillRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.nio.charset.StandardCharsets;

/**
 * @author
 * @date 2020/12/27 0:21
 */
@Component
@Slf4j
public class PromoMessageProvider {
    //    //普通消息的生产者
//    private DefaultMQProducer mqProducer;
//事务型消息的生产者
    private TransactionMQProducer transactionMQProducer;
    @Autowired
    PromoItemMapper promoItemMapper;
    @Autowired
    CacheManager cacheManager;

    public static final String PROMO_ORDER_TAG = "promo_order_tag_";
    public static final String FAIL = "fail";
    public static final String SUCCESS = "success";
    public static final String PROMO_ORDER_SECKILL_TOPIC = "promo_order_seckill";

    @PostConstruct
    public void init() {
        //初始化对象
        transactionMQProducer = new TransactionMQProducer("promo_Producer");
        //设置事务注册中心
        transactionMQProducer.setNamesrvAddr("127.0.0.1:9876");
        //设置事务监听器
        transactionMQProducer.setTransactionListener(new TransactionListener() {
            //执行本地事务  扣减库存
            @Override
            public LocalTransactionState executeLocalTransaction(Message message, Object o) {
//                log.error("sss");
                SecKillRequest request = (SecKillRequest) o;

                Integer row = promoItemMapper.decreaseStock(request.getPsId(), request.getProductId());


                String key = PROMO_ORDER_TAG + message.getTransactionId();


                if (row < 1) {
                    //扣减库存未成功 返回rollbackMessage
                    //在redis缓存里设一个标记 失败 过期时间 1天
                    cacheManager.setCache(key, FAIL, 1);
                    return LocalTransactionState.ROLLBACK_MESSAGE;
                }
                cacheManager.setCache(key, SUCCESS, 1);
                return LocalTransactionState.COMMIT_MESSAGE;
            }

            //检查本地事务
            @Override
            public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {
                String key = PROMO_ORDER_TAG + messageExt.getTransactionId();
                String value = cacheManager.checkCache(key);
                if (StringUtils.isBlank(value)) {
                    //返回的是unknow 则过一会会回来重新查
                    return LocalTransactionState.UNKNOW;
                }
                if (SUCCESS.equals(value)) {
                    return LocalTransactionState.COMMIT_MESSAGE;
                }

                return LocalTransactionState.ROLLBACK_MESSAGE;
            }
        });

        try {
            transactionMQProducer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    public boolean sendMessage(SecKillRequest request) {



        Message message = new Message();
        message.setTopic(PROMO_ORDER_SECKILL_TOPIC);
        String body = JSON.toJSONString(request);

        message.setBody(body.getBytes(StandardCharsets.UTF_8));
        Object args = request;

        TransactionSendResult sendResult = null;
        try {
            sendResult= transactionMQProducer.sendMessageInTransaction(message, args);
        } catch (MQClientException e) {
            e.printStackTrace();
        }
        if (sendResult == null) {
            return false;
        }
        //获取本地事务的执行结果
        LocalTransactionState localTransactionState = sendResult.getLocalTransactionState();
        if (localTransactionState.equals(LocalTransactionState.COMMIT_MESSAGE)) {
            return true;
        }

        log.info("消息发送失败,{}", JSON.toJSONString(sendResult));

        return false;
    }


    @PreDestroy
    public void destroy(){
        transactionMQProducer.shutdown();
    }
}
